package com.qidianit.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.ProschedueTask;
import com.qidianit.mes.pojo.pro.Workflow;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.mapper.ProductionOrderMapper;
import com.qidianit.mes.pro.mapper.WorkflowMapper;
import com.qidianit.mes.pro.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: YanJiRan
 * @Date: 2025/9/18 - 下午1:37
 */
@Service
public class WorkflowServiceImpl implements WorkflowService {
    @Autowired
    private WorkflowMapper workflowMapper;
    @Autowired
    private ProcessMapper processMapper;

    @Override
    public Result<List<Workflow>> selectListByMaterialCode(String code) {
        List<Workflow> workflows = workflowMapper.selectListByMaterialCode(code);
        workflows.forEach(workflow -> {
            workflow.setProcesses(processMapper.selectProcessByWorkflowId(workflow.getId()));
        });
        return Result.success(workflows);
    }

    @Override
    public Result<PageInfo<Workflow>> selectList(Workflow workflow, int page, int size) {
        //开启分页
        PageHelper.startPage(page,size);
        List<Workflow> workflows = workflowMapper.selectList(workflow);
        return Result.success(new PageInfo<>(workflows));
    }

    @Override
    public Result<Workflow> selectByCode(String workflowCode) {
        return Result.success(workflowMapper.selectByCode(workflowCode));
    }

    @Override
    public Result<Workflow> saveWorkflow(Workflow workflow) {
        Workflow workflow1 = workflowMapper.selectByCode(workflow.getWorkflowCode());
        if (workflow1 != null) {
            return Result.error("工艺编码已存在，请更换编码后重试");
        }
        return workflowMapper.saveWorkflow(workflow) == 1 ? Result.success(workflow) : Result.error("操作失败");
    }

    @Override
    public Result updateById(Workflow workflow) {
        //先根据编码查询是否存在相同编码的工序
        Workflow workflow1 = workflowMapper.selectByCode(workflow.getWorkflowCode());
        //如果存在相同编码的工序
        if (workflow1 != null) {
            //检查id是否相同，不同则说明编码重复
            if (!workflow1.getId().equals(workflow.getId())) {
                return Result.error("工艺编码已存在，请更换编码后重试");
            }
        }
        return workflowMapper.updateById(workflow) == 1 ? Result.success() : Result.error("操作失败");
    }

    @Override
    public Result deleteById(Long id) {
        return workflowMapper.deleteById(id) == 1 ? Result.success() : Result.error("操作失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return workflowMapper.batchDelete(ids) > 0 ? Result.success() : Result.error("操作失败");
    }
}
